<template>
	<section id='page__goods-category'>
		<header class="page__header">
			<h2 class="page__title">商品类别</h2>
			<el-button
				size="mini"
				type="primary"
				@click="editCategory(null)"
			>
				新增类别
			</el-button>
		</header>
		<div class="page__main">
			<div class="operate-bar">
				<div class="bar-main">
					<el-input
						v-model="keyword"
						@keyup.enter.native="search"
						style="width: 260px"
						size="small"
						placeholder="请输入关键词">
						<i
							slot="suffix"
							class="el-input__icon el-icon-search"
							@click="search"
						></i>
					</el-input>
				</div>
				<div class="bar-sub">

				</div>
			</div>
			<el-table
				:data="tableDataPerPage"
				style="width: 100%">
				<el-table-column
					prop="id"
					label="ID"
					width="100px"
				>
				</el-table-column>
				<el-table-column
					prop="name"
					label="类别"
				>
				</el-table-column>
				<el-table-column
					prop="createTime"
					label="创建时间"
				>
				</el-table-column>
				<el-table-column
					prop="updateTime"
					label="更新时间"
				>
				</el-table-column>
				<el-table-column
					label="状态"
				>
					<template slot-scope="prop">
						<el-tag
							v-if="!prop.row.parentId"
							type="success">主类别</el-tag>
						<el-tag
							v-else
							type="warning">二级类别</el-tag>
					</template>
				</el-table-column>
				<el-table-column
					label="操作"
				>
					<template slot-scope="prop">
						<el-button
							type="warning"
							size="mini"
							@click="editCategory(prop.row)"
						>
							编辑
						</el-button>
						<el-button
							type="danger"
							size="mini"
							@click="deleteCategory(prop.row)"
						>
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				background
				layout="prev, pager, next"
				hide-on-single-page
				:page-size="pagination.size"
				:current-page="pagination.page"
				:total="total"
				@current-change="changePage"
			>
			</el-pagination>
		</div>
		<el-dialog
			:title="title"
			:visible.sync="dialogVisible"
			:append-to-body="true"
			custom-class="dialog__goods-category"
			width="30%"
		>
			<el-form
				ref="form"
				:model="form"
				:rules="rules"
				label-width="82px">
				<el-form-item label="类别名称" prop="name">
					<el-input
						v-model="form.name"
						@input="changeName"
						@blur="validateName"
						size="small"
						placeholder="请输入类别名称">
						<i
							v-if="nameLoading"
							slot="suffix"
							class="el-input__icon el-icon-loading"></i>
					</el-input>
				</el-form-item>
				<el-form-item label="所属主类别" style="margin-top: 22px">
					<el-select
						style="width: 100%"
						v-model="form.parentId"
						size="small"
						placeholder="所属主类别，可不选">
						<el-option
							v-for="item in mainCategories"
							:key="item.id"
							:label="item.name"
							:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
		    <el-button
			    size="mini"
			    @click="dialogVisible = false">
			    取消
		    </el-button>
		    <el-button
			    type="primary"
			    size="mini"
			    @click="saveCategory">
			    确定
		    </el-button>
		  </span>
		</el-dialog>
	</section>
</template>

<script>
  /**
   *
   *
   *
   */
  import * as CONSTANT from '../../config/constant'
  import {mapState} from 'vuex'

  export default {
    name: "category",
    data() {
      return {
        ...CONSTANT,
        keyword: '',
        pagination: {
          page: 1,
          size: CONSTANT.PAGE_SIZE
        },
        loading: false,
        submitLoading: false,
        nameLoading: false,
        tableData: [],
        dialogVisible: false,
        targetCategory: null,
        form: {
          name: '',
          parentId: ''
        },
        rules: {
          name: [{required: true, message: '请输入类别名称'}, {
            validator: (rule, value, callback) => {
              callback(this.nameError)
            },
            trigger: 'change'
          }]
        },
        nameError: undefined
      }
    },
    computed: {
      ...mapState([
        'categories'
      ]),
      title() {
        let targetCategory = this.targetCategory
        if (!targetCategory) return '创建类别'
        return '编辑' + targetCategory.name
      },
      mainCategories() {
        let targetCategory = this.targetCategory || {}
        return this.categories.filter(item => {
          return !item.parentId && item.id !== targetCategory.id
        })
      },
      total() {
        return this.categories.length
      },
      tableDataPerPage() {
        let {page, size} = this.pagination,
          tableData = this.categories
        return tableData.slice((page - 1) * size, page * size)
      },
      params() {
        let params = {
          ...this.targetCategory,
          name: this.form.name,
	        parentId: this.form.parentId
        }
        delete params.createTime
        delete params.updateTime
	      delete params.children
        return params
      }
    },
    watch: {
      nameError() {
        this.$refs.form.validateField('name')
      }
    },
    mounted() {
      this.search()
    },
    methods: {
      changeName() {
        this.nameError = undefined
      },
      validateName() {
        this.nameLoading = true
        this.$axios.post('/category/isNameValid', this.params)
          .then(({success, message}) => {
            this.nameError = success ? undefined : message
          })
          .catch(({message}) => {
            this.$message({
              type: 'error',
              message: message
            })
          })
          .finally(() => {
            this.nameLoading = false
          })
      },
      search() {
        this.pagination.page = 1
        this.getList()
      },
      changePage(page) {
        this.pagination.page = page
      },
      async getList() {
        this.loading = true
        await this.$store.dispatch('getCategories', this.keyword)
        this.loading = false
      },
      editCategory(category) {
        this.targetCategory = category
        this.form.name = category && category.name || ''
	      this.form.parentId = category && category.parentId || ''
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs.form && this.$refs.form.clearValidate()
        })
      },
      saveCategory() {
        this.$refs.form.validate(valid => {
          if (!valid) return false
          this.submitLoading = true

          this.$axios.post('/category/save', this.params)
            .then(({success, message}) => {
              if (success) {
                this.dialogVisible = false
                this.getList()
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
              } else {
                if (/类别/.test(message)) {
                  this.nameError = message
                } else {
                  this.$message({
                    type: 'error',
                    message: message
                  })
                }
              }
            })
            .catch(({message}) => {
              this.$message({
                type: 'error',
                message: message
              })
            })
            .finally(() => {
              this.submitLoading = false
            })
        })
      },
      deleteCategory(category) {
        this.$confirm(`确认删除 ${category.name} ?`, '删除类别', {
          beforeClose: (action, instance, done) => {
            if (action !== 'confirm') {
              done()
              return false
            }
            this.$axios.post('/category/delete', {
                id: category.id
              })
              .then(({success, message}) => {
                if (success) {
                  this.$message({
                    type: 'success',
                    message: '删除成功'
                  })
                  this.getList()
                } else {
                  this.$message({
                    type: 'error',
                    message: message
                  })
                }
              })
              .catch(({message}) => {
                this.$message({
                  type: 'error',
                  message: message
                })
              })
              .finally(() => {
                done()
              })
          }
        })
      }
    }
  }
</script>

<style lang='less'>
	#page__goods-category {

	}

	.dialog__goods-category {
		.el-form-item {
			margin-bottom: 0;
		}
	}
</style>
